/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-02-17
*/
package com.rzico.basics.service;

import com.rzico.base.BaseMapper;
import com.rzico.base.CommResult;
import com.rzico.base.impl.BaseServiceImpl;
import com.rzico.basics.entity.*;
import com.rzico.basics.model.MapPoint;
import com.rzico.basics.model.ShopExtVo;
import com.rzico.basics.model.ShopVo;
import com.rzico.core.entity.SysMch;
import com.rzico.core.service.SysMchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.rzico.basics.mapper.ShopMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <pre>
 * 会员业务类
 * </pre>
 *
 * @author Rzico Boot
 * @version 1.0
 */
@Service
public class ShopService extends BaseServiceImpl<Shop, String> {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private SysMchService sysMchService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private ShopTagService shopTagService;

    @Override
    public BaseMapper<Shop, String> getMapper() {
        return shopMapper;
    }


    @Transactional(rollbackFor = Exception.class)
    public ShopExtVo saveMchShop(ShopExtVo vo,String username,String password,Long [] tagIds) {

        Enterprise isv = enterpriseService.getCurrent();

        SysMch sysMch = new SysMch();
        sysMch.setLogo(vo.getLogo());
        sysMch.setShortName(vo.getName());
        sysMch.setName(vo.getName());
        sysMch.setAddress(vo.getAddress());
        sysMch.setAreaName(vo.getAreaName());
        sysMch.setAreaId(vo.getAreaId());
        sysMch.setScopeType(vo.getScopeType());
        sysMch.setPhone(vo.getTelephone());
        sysMch.setStatus(0);
        sysMch.setDelFlag(false);
        sysMch.setMchType(2);
        sysMch.setLinkman(vo.getLinkman());
        sysMch.setIsvId(isv.getMchId());

        sysMchService.save(sysMch,username,password);

        Enterprise enterprise = enterpriseService.initEnterprise(sysMch);

        Shop shop = findByPoint(enterprise,0d,0d);
        //初始化企业
        shop.setScopeType(vo.getScopeType());
        shop.setLat(vo.getLat());
        shop.setLng(vo.getLng());
        shop.setStatus(0);
        shop.setPrinterp(vo.getPrinterp());
        shop.setPrinteru(vo.getPrinteru());
        shop.setShopCategoryId(vo.getShopCategoryId());
        shop.setRiderNo(vo.getRiderNo());
        shop.setRiderPluginId(vo.getRiderPluginId());
        if ("".equals(shop.getRiderPluginId())) {
            shop.setRiderPluginId(null);
        }

        updateByPrimaryKeySelective(shop);

        enterprise.setLogo(vo.getLogo());
        enterprise.setName(vo.getName());
        enterprise.setBrokerage(vo.getBrokerage());
        enterprise.setPaybill(vo.getPaybill());
        enterprise.setBankId(vo.getBankId());
        enterprise.setBankName(vo.getBankName());
        enterprise.setBankNum(vo.getBankNum());
        enterprise.setBankType(vo.getBankType());

        enterprise.setFood(vo.getFood());
        enterprise.setThedoor(vo.getThedoor());
        enterprise.setScene(vo.getScene());
        enterprise.setLicense(vo.getLicense());
        enterprise.setIdCardBack(vo.getIdCardBack());
        enterprise.setIdCardFront(vo.getIdCardFront());

        enterprise.setContent(vo.getContent());
        enterprise.setDeliverMethod(vo.getDeliverMethod());
        enterprise.setMinimumDelivery(vo.getMinimumDelivery());

        enterprise.setShippingConfig(vo.getShippingConfig());
        enterprise.setShippingMethod(vo.getShippingMethod());

        enterprise.setPaused(vo.getPaused());
        enterprise.setNotice(vo.getNotice());

        enterpriseService.updateByPrimaryKeySelective(enterprise);

        if (tagIds!=null) {
            for (Long tagId : tagIds) {
                ShopTag adTag = new ShopTag();
                adTag.setShops(shop.getId());
                adTag.setTags(tagId);
                shopTagService.insert(adTag);
            }
        }


        return vo;

    }


    @Transactional(rollbackFor = Exception.class)
    public ShopExtVo updateMchShop(ShopExtVo vo,Long [] tagIds) {

        SysMch sysMch = sysMchService.selectByPrimaryKey(vo.getMchId());
        if (vo.getLogo()!=null) {
            sysMch.setLogo(vo.getLogo());
        }
        if (vo.getName()!=null) {
            sysMch.setShortName(vo.getName());
            sysMch.setName(vo.getName());
        }
        if (vo.getAddress()!=null) {
            sysMch.setAddress(vo.getAddress());
        }
        if (vo.getAreaName()!=null) {
            sysMch.setAreaName(vo.getAreaName());
        }
        if (vo.getAreaId()!=null) {
            sysMch.setAreaId(vo.getAreaId());
        }
        if (vo.getScopeType()!=null) {
            sysMch.setScopeType(vo.getScopeType());
        }
        if (vo.getTelephone()!=null) {
            sysMch.setPhone(vo.getTelephone());
        }
      //  sysMch.setStatus(0);
        sysMch.setDelFlag(false);
      //  sysMch.setMchType(2);
        if (vo.getLinkman()!=null) {
            sysMch.setLinkman(vo.getLinkman());
        }

        sysMchService.updateByPrimaryKeySelective(sysMch);

        Shop shop = findById(vo.getId());
        //初始化企业
        shop.setName(vo.getName());
        shop.setAddress(vo.getAddress());
        shop.setAreaName(vo.getAreaName());
        shop.setAreaId(vo.getAreaId());
        shop.setTelephone(vo.getTelephone());
        shop.setLinkman(vo.getLinkman());

        shop.setScopeType(vo.getScopeType());
        shop.setLat(vo.getLat());
        shop.setLng(vo.getLng());
        //shop.setStatus(0);
        shop.setPrinterp(vo.getPrinterp());
        shop.setPrinteru(vo.getPrinteru());
        shop.setShopCategoryId(vo.getShopCategoryId());
        shop.setRiderNo(vo.getRiderNo());
        shop.setRiderPluginId(vo.getRiderPluginId());
        if ("".equals(shop.getRiderPluginId())) {
            shop.setRiderPluginId(null);
        }

        updateByPrimaryKeySelective(shop);

        Enterprise enterprise = enterpriseService.findByMch(vo.getMchId());

        enterprise.setLogo(vo.getLogo());
        enterprise.setName(vo.getName());
        enterprise.setBrokerage(vo.getBrokerage());
        enterprise.setPaybill(vo.getPaybill());
        enterprise.setBankId(vo.getBankId());
        enterprise.setBankName(vo.getBankName());
        enterprise.setBankNum(vo.getBankNum());
        enterprise.setBankType(vo.getBankType());

        enterprise.setFood(vo.getFood());
        enterprise.setThedoor(vo.getThedoor());
        enterprise.setScene(vo.getScene());
        enterprise.setLicense(vo.getLicense());
        enterprise.setIdCardBack(vo.getIdCardBack());
        enterprise.setIdCardFront(vo.getIdCardFront());

        enterprise.setContent(vo.getContent());
        enterprise.setDeliverMethod(vo.getDeliverMethod());
        enterprise.setMinimumDelivery(vo.getMinimumDelivery());
        enterprise.setBackground(vo.getBackground());

        enterprise.setShippingConfig(vo.getShippingConfig());
        enterprise.setShippingMethod(vo.getShippingMethod());
        enterprise.setNotice(vo.getNotice());

        enterprise.setPaused(vo.getPaused());

        enterpriseService.updateByPrimaryKeySelective(enterprise);

        ShopTag shopTag = new ShopTag();
        shopTag.setShops(shop.getId());
        shopTagService.delete(shopTag);


        if (tagIds!=null) {
            for (Long tagId : tagIds) {
                ShopTag adTag = new ShopTag();
                adTag.setShops(shop.getId());
                adTag.setTags(tagId);
                shopTagService.insert(adTag);
            }
        }


        return vo;
    }

    @Transactional(rollbackFor = Exception.class)
    public void auditMchShop(ShopExtVo vo) {

        Enterprise enterprise = enterpriseService.selectByPrimaryKey(vo.getEnterpriseId());
        enterprise.setPaused(0);
        enterpriseService.updateByPrimaryKeySelective(enterprise);

        SysMch sysMch = sysMchService.selectByPrimaryKey(vo.getMchId());
        sysMch.setStatus(1);
        sysMchService.updateByPrimaryKeySelective(sysMch);

        Shop shop = findById(vo.getId());
        shop.setStatus(1);
        updateByPrimaryKeySelective(shop);

    }



    @Transactional(rollbackFor = Exception.class)
    public void closeMchShop(ShopExtVo vo) {

        Enterprise enterprise = enterpriseService.selectByPrimaryKey(vo.getEnterpriseId());
        enterprise.setPaused(2);
        enterpriseService.updateByPrimaryKeySelective(enterprise);

        SysMch sysMch = sysMchService.selectByPrimaryKey(vo.getMchId());
        sysMch.setStatus(2);
        sysMchService.updateByPrimaryKeySelective(sysMch);

        Shop shop = findById(vo.getId());
        shop.setStatus(2);
        updateByPrimaryKeySelective(shop);

    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteByIds(Object [] ids) {
        int rw = 0;
        for (Object id:ids) {
            Shop shop = selectByPrimaryKey(id);
            shop.setDeleted(true);
            rw = rw + super.updateByPrimaryKeySelective(shop);
        }
        return rw;
    }

    //查找离我最近的门店
    public Shop findByPoint(Enterprise enterprise,Double lat,Double lng) {

        if (lat==null) {
            lat = 0d;
        }

        if (lng==null) {
            lng = 0d;
        }

        Map<String,Object> params = new HashMap<>();
        params.put("enterpriseId",enterprise.getId());
        params.put("sortField","id");
        params.put("sortType","asc");

        MapPoint point = new MapPoint();
        point.setLat(lat);
        point.setLng(lng);

        Shop mshop = null;
        Double d = 0d;

        List<Shop> shopList = shopMapper.selectList(params);
        if (lat==0 && lng==0 && shopList.size()>0) {
            return shopList.get(0);
        }
        for (Shop shop:shopList) {
            //在配送范围，判断离谁近
            Double dt = 9999999d;
            if (shop.getLat()==null) {
                shop.setLat(0d);
            }
            if (shop.getLng()==null) {
                shop.setLng(0d);
            }
            if (shop.getLat()>0 && shop.getLat()>0) {
                MapPoint shopPoint = new MapPoint();
                shopPoint.setLat(shop.getLat());
                shopPoint.setLng(shop.getLng());
                dt = point.distatce(shopPoint);
            }
            if (d.compareTo(0d)==0) {
                d = dt;
                mshop = shop;
            } else {
                if (d.compareTo(dt)>0) {
                    d = dt;
                    mshop = shop;
                }
            }
        }
        return mshop;
    }


    //查找离我最近的门店
    public Shop findByISV(Enterprise enterprise,Double lat,Double lng) {

        if (lat==null) {
            lat = 0d;
        }

        if (lng==null) {
            lng = 0d;
        }

        Map<String,Object> params = new HashMap<>();
        params.put("isvId",enterprise.getMchId());

        MapPoint point = new MapPoint();
        point.setLat(lat);
        point.setLng(lng);

        Shop mshop = null;
        Double d = 0d;

        List<Shop> shopList = shopMapper.selectList(params);
        for (Shop shop:shopList) {
            //在配送范围，判断离谁近
            Double dt = 9999999d;
            if (shop.getLat()==null) {
                shop.setLat(0d);
            }
            if (shop.getLng()==null) {
                shop.setLng(0d);
            }
            if (shop.getLat()>0 && shop.getLat()>0) {
                MapPoint shopPoint = new MapPoint();
                shopPoint.setLat(shop.getLat());
                shopPoint.setLng(shop.getLng());
                dt = point.distatce(shopPoint);
            }
            if (d.compareTo(0d)==0) {
                d = dt;
                mshop = shop;
            } else {
                if (d.compareTo(dt)>0) {
                    d = dt;
                    mshop = shop;
                }
            }
        }
        return mshop;
    }

    public List<ShopVo> selectLbsList(Map<String, Object> params,Double lat,Double lng) {
        List<ShopVo> shopList = shopMapper.selectLbsList(params);
        if (lat!=null && lng !=null) {
            for (ShopVo shopVo : shopList) {
                if (shopVo.getLat() != null && shopVo.getLng() != null) {
                    MapPoint point = new MapPoint();
                    point.setLng(lng);
                    point.setLat(lat);

                    MapPoint shopPoint = new MapPoint();
                    shopPoint.setLat(shopVo.getLat());
                    shopPoint.setLng(shopVo.getLng());

                    Double d = point.distatce(shopPoint);
                    shopVo.setDistance(d);
                }
            }
            //开始排序
            Collections.sort(shopList, new Comparator<ShopVo>() {
                public int compare(ShopVo n1, ShopVo n2) {
                    if (n1.getDistance()==null) {
                        return -1;
                    }
                    if (n2.getDistance()==null) {
                        return 1;
                    }
                    return n1.getDistance().compareTo(n2.getDistance());
                }
            });
        }

        return shopList;
    }


    public ShopVo findShopVo(Long id) {
        Map<String, Object> params = new HashMap<String, Object>();

        params.put("id",id);

        List<ShopVo> list = selectLbsList(params,0d,0d);

        if (list.size()>0) {
            return list.get(0);
        } else {
            return null;
        }

    }

    public List<ShopVo> selectAffiliatedList(Map<String, Object> params) {
        List<ShopVo> list = shopMapper.selectAffiliatedList(params);
        return list;
    }

    public List<ShopVo> selectChefAffiliatedList(Map<String, Object> params) {
        List<ShopVo> list = shopMapper.selectChefAffiliatedList(params);
        return list;
    }

    public ShopVo findShopVoParams(Map<String, Object> voParams) {
        ShopVo shopVo = shopMapper.findShopVoParams(voParams);
        return shopVo;
    }
}
